package org.duomn.ichat.thread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TCPReceiverThread extends Thread {
	private static Logger logger = LoggerFactory.getLogger(TCPReceiverThread.class);
//	public static int LISTEN_PORT = 9080;
	
	ServerSocket ss = null;
	boolean isrunning;
	
	private int port;
	
	public TCPReceiverThread(int port) {
		this.port = port;
		try {
			ss = new ServerSocket(this.port);
			isrunning = true;
			logger.info("监听线程启动完成，监听在" + port + "端口");
		} catch (IOException e) {
			logger.error("启动监听线程失败", e);
		}
	}
	
	public void run() {
		while (isrunning) {
			try {
				Socket s = ss.accept(); // 阻塞式的方法
				TCPThreadPASV pasvChat = new TCPThreadPASV(s);
				pasvChat.openSession(); // 打开失败，不启动线程
			} catch (SocketException e) {
				if (isrunning) { 
					logger.warn("监听线程关闭发生异常", e);
				}
			} catch (IOException e) {
				logger.warn("监听线程启动后台线程时发生异常.", e);
			}
		}
		logger.info("监听线程正常退出");
	}
	
	public void close() {
		if (!isrunning) return;
		isrunning = false;
		try {
			ss.close();
		} catch (IOException e) {
			logger.error("监听线程关闭发生异常", e);
		}
	}

}
